package com.sec.android.app.myfiles.thumbnail;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;

import com.sec.android.app.myfiles.info.FileType;
import com.sec.android.app.myfiles.info.MediaFile;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;

public class ApkThumbnailImp extends ThumbnailImp {

    public ApkThumbnailImp(Context context) {
        super(context);
    }

    @Override
    protected boolean isSupport(FileRecord record) {
        boolean bRet = false;
        if (record.getFileType() == FileType.APK) {
            bRet = true;
        }
        return bRet;
    }

    @Override
    public Bitmap _createThumbnail(FileRecord record, int thumbnailSize) {
        Bitmap retBmp = null;

        PackageManager mPkgMgr = mContext.getPackageManager();
        if (mPkgMgr != null) {
            PackageInfo mPkgInfo = mPkgMgr.getPackageArchiveInfo(record.getFullPath(), PackageManager.GET_ACTIVITIES);
            if (mPkgInfo != null) {
                try {
                    Drawable icon = null;
                    ApplicationInfo appInfo = mPkgInfo.applicationInfo;
                    appInfo.sourceDir = record.getFullPath();
                    appInfo.publicSourceDir = record.getFullPath();
                    if (appInfo.icon != 0) {
                        icon = appInfo.loadIcon(mContext.getPackageManager());
                    }

                    if (icon != null) {
                        retBmp = getResBitmap(icon, thumbnailSize);
                    }

                } catch (OutOfMemoryError e) {
                    Log.e(this, "OutOfMemoryError:" + e.toString());
                }
            }
        }

        if (retBmp == null) {
            retBmp = BitmapFactory.decodeResource(mContext.getResources(), MediaFile.getIcon(mContext, record));
        }

        return retBmp;
    }

    private Bitmap getResBitmap(Drawable d, int thumbnailSize) throws OutOfMemoryError {
        Bitmap retBmp = Bitmap.createBitmap(thumbnailSize, thumbnailSize, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(retBmp);
        c.drawColor(0, PorterDuff.Mode.CLEAR);
        d.setBounds(0, 0, thumbnailSize - 1, thumbnailSize - 1);
        d.draw(c);
        return retBmp;
    }

}
